package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.mapper.UserMapper;
import com.fjh.springboot_01.pojo.User;
import com.fjh.springboot_01.service.UserService;
import com.fjh.springboot_01.utils.Md5Util;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public void register(String username, String password, String email, Integer role) {
        String md5String = Md5Util.getMD5String(password);
        userMapper.add(username, md5String, email, role);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd), id);
    }

    @Override
    public List<User> getPendingTeachers() {
        return userMapper.getPendingTeachers();
    }

    @Override
    public void handleTeacherApproval(Integer userId, Integer status) {
        userMapper.updateTeacherStatus(userId, status);
    }

    @Override
    public List<User> getUsersByRole(Integer role) {
        return userMapper.getUsersByRole(role);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public void updateUserStatus(Integer userId, Integer status) {
        userMapper.updateUserStatus(userId, status);
    }

    @Override
    public void deleteUser(Integer userId) {
        userMapper.deleteUser(userId);
    }

    @Override
    public List<User> getPopularTeachers(int limit) {
        return userMapper.getPopularTeachers(limit);
    }

    @Override
    public int getTeacherCount() {
        return userMapper.getTeacherCount();
    }

    @Override
    public int getStudentCount() {
        return userMapper.getStudentCount();
    }

    @Override
    public void resetPassword(String username, String newPassword) {
        User user = userMapper.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.updatePwd(Md5Util.getMD5String(newPassword), user.getId());
    }
}
